package com.tbl.modules.wms.service.Impl.inventory;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.dao.baseinfo.WarehouseDAO;
import com.tbl.modules.wms.dao.inventory.InventoryDAO;
import com.tbl.modules.wms.entity.inventory.Inventory;
import com.tbl.modules.wms.entity.storageinfo.StorageInfo;
import com.tbl.modules.wms.service.inventory.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 盘点计划实现类
 * @author 70486
 */
@Service("inventoryService")
public class InventoryServiceImpl extends ServiceImpl<InventoryDAO, Inventory> implements InventoryService {

	/**
	 * 盘点任务dao
	 */
	@Autowired
	private InventoryDAO inventoryDAO;
	/**
	 * 仓库
	 */
	@Autowired
	private WarehouseDAO warehouseDAO;

	/**
	 * 查询盘点数据列表
	 * @param pageTbl
	 * @param params
	 * @return PageUtils
	 */
	@Override
	public PageUtils getInventoryPlanList(PageTbl pageTbl, Map<String,Object> params) {
		Page page = new Page(pageTbl.getPageno(), pageTbl.getPagesize(), pageTbl.getSortname(), "asc".equalsIgnoreCase(pageTbl.getSortorder()));
		List<Inventory> lstInventory = inventoryDAO.selectInventoryList(page, params);

		if (lstInventory!=null){
			lstInventory.forEach(inventory -> {
				inventory.setFactoryname(StringUtils.listToString(warehouseDAO.findWarehouseNameByCode(Arrays.asList(inventory.getFactorycode().split(",")))));
				inventory.setUserName(StringUtils.listToString(inventoryDAO.getUserNameByUserId( Arrays.asList(inventory.getUserId().split(",")))));
			});
		}

		return new PageUtils(page.setRecords(lstInventory));
	}

	/**
	 * 查询盘点审核列表
	 * @param pageTbl
	 * @param params
	 * @return PageUtils
	 */
	@Override
	public PageUtils getInventoryReviewList(PageTbl pageTbl, Map<String, Object> params) {
		Page page = new Page(pageTbl.getPageno(), pageTbl.getPagesize(), pageTbl.getSortname(), "asc".equalsIgnoreCase(pageTbl.getSortorder()));
		List<Inventory> lstInventory = inventoryDAO.selectInventoryReviewList(page, params);

		if (lstInventory!=null){
			lstInventory.forEach(inventory -> {
				inventory.setFactoryname(StringUtils.listToString(warehouseDAO.findWarehouseNameByCode(Arrays.asList(inventory.getFactorycode().split(",")))));
				inventory.setUserName(StringUtils.listToString(inventoryDAO.getUserNameByUserId( Arrays.asList(inventory.getUserId().split(",")))));
			});
		}

		return new PageUtils(page.setRecords(lstInventory));
	}

	/**
	 * 获得自增主键
	 * @return Long 主键
	 */
	@Override
	public Long getSequence() {
		return inventoryDAO.getSequence();
	}
	
	/**
	 * 获取最大盘点编号
	 * @return int 盘点编号
	 */
	@Override
	public int getMaxCode() {
		return inventoryDAO.getMaxCode();
	}
	
	/**
     * 获取导出列
     * @param ebsCode	ebs盘点单号
     * @param userId	用户主键
     * @return List<StorageInfo>
     */
    @Override
    public List<StorageInfo> getAllLists(String ebsCode, Long userId) {
		//仓库
		StringBuffer buffer = new StringBuffer();
		//盘点表主键
		StringBuffer buffer1 = new StringBuffer();
		inventoryDAO.selectList(new EntityWrapper<Inventory>().eq("EBS_CODE",ebsCode)).forEach(inventory -> {
			buffer.append(inventory.getFactorycode()).append(",");
			buffer1.append(inventory.getId()).append(",");
		});
		Map<String, Object> map = Maps.newHashMap();
		//盘的仓库
		map.put("warehouseIds", Arrays.asList(buffer.toString().split(",")));
		map.put("wmsCodePlanId", Arrays.asList(buffer1.toString().split(",")));
        return inventoryDAO.getAllLists(map);
    }
    
    /**
     * 获得导出列表数据
     * @param response
     * @param ebsCode
     * @param lstStorageInfo
     */
    @Override
	public void toExcel(HttpServletResponse response, String ebsCode, List<StorageInfo> lstStorageInfo) {
        try {
            String sheetName = "盘点审核清单" +ebsCode+ "(" + DateUtils.getDay() + ")";

			response.setHeader("Content-Type", "application/force-download");
			response.setHeader("Content-Type", "application/vnd.ms-excel");
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Expires", "0");
			response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
			response.setHeader("Pragma", "public");
			response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
					"ISO8859-1") + ".xls");

			List<Inventory> lstInventory = inventoryDAO.selectList(new EntityWrapper<Inventory>().eq("EBS_CODE", ebsCode));
			Date auditDate = lstInventory.get(0).getAuditDate();
			lstStorageInfo.forEach(storageInfo -> {
				if("1".equals(storageInfo.getResult())){
					storageInfo.setResult("正常");
				}else if("2".equals(storageInfo.getResult())){
					storageInfo.setResult("盘盈");
				}else if("3".equals(storageInfo.getResult())){
					storageInfo.setResult("盘亏");
				}else if("4".equals(storageInfo.getResult())){
					storageInfo.setResult("错位正常");
				}else if("5".equals(storageInfo.getResult())){
					storageInfo.setResult("错位盘盈");
				}else if("6".equals(storageInfo.getResult())){
					storageInfo.setResult("错位盘亏");
				}else {
					//确认的审核日期auditDate

					//入库日期
					Date instorageDay = storageInfo.getInStorageTime();
					if (DateUtils.dateToLong(auditDate) > DateUtils.dateToLong(instorageDay)){
						storageInfo.setResult("漏盘");
					} else {
						storageInfo.setResult("新入库");
					}
				}

				if (storageInfo.getShelfState() == null){
					storageInfo.setStateName("未盘点");
				}else if(storageInfo.getShelfState() == 0){
					storageInfo.setStateName("移库失败");
				}else if(storageInfo.getShelfState() == 1){
					storageInfo.setStateName("移库成功");
				}else if(storageInfo.getShelfState() == 2){
					storageInfo.setStateName("无需移库");
				}else if (storageInfo.getShelfState() == 3) {
					storageInfo.setStateName("移库待执行");
				}

				if (storageInfo.getState() == null){
					storageInfo.setFactoryCode("未盘点");
				}else if(storageInfo.getState() == 0){
					storageInfo.setFactoryCode("同步数量失败");
				}else if(storageInfo.getState() == 1){
					storageInfo.setFactoryCode("同步数量成功");
				}else if (storageInfo.getState() == 3) {
					storageInfo.setFactoryCode("同步数量待执行");
				}

				if (storageInfo.getUploadTime()!=null){
					storageInfo.setUploadTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(storageInfo.getUploadTime()));
				}
				if (storageInfo.getInStorageTime()!=null){
					storageInfo.setInStorageName(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(storageInfo.getInStorageTime()));
				}
			});

            Map<String, String> mapFields = new LinkedHashMap<>();
            mapFields.put("result", "盘点结果");
			mapFields.put("stateName", "审核库位状态");
			mapFields.put("factoryCode", "审核米数状态");
			mapFields.put("qaCode", "质保单号");
			mapFields.put("batchNo", "批次号");
			mapFields.put("meter", "库存米数");
			mapFields.put("inventoryMeter", "盘点米数");
			mapFields.put("shelfCode", "库存库位");
			mapFields.put("inventoryShelf", "盘点库位");
			mapFields.put("inventoryName", "盘点人");
			mapFields.put("uploadTimeStr", "盘点时间");
			mapFields.put("inStorageName", "入库时间");
			mapFields.put("dishcode", "盘号");
			mapFields.put("materialCode", "物料编码");
            DeriveExcel.exportExcel(sheetName, lstStorageInfo, mapFields, response, "");
        } catch (Exception e) {
            e.printStackTrace();
        }
	}

    /**
     * 获取厂区列表
     * @param  list
     * @return List<Map<String, Object>>
     */
	@Override
	public List<Map<String, Object>> getFactoryList(List<String> list) {
		return inventoryDAO.getFactoryList(list);
	}

	/**
	 * 确认审核日期
	 * @param ebsCode
	 * @param date
	 */
	@Override
	public void confirmAuditTime(String ebsCode, Date date){
		inventoryDAO.confirmAuditTime(ebsCode, date);
	}
}
